import http from 'wechat-http'
http.baseURL = 'https://live-api.itheima.net'

http.intercept.response=({data})=>{
  return data
}
wx.http=http
// 请求拦截器
http.intercept.request = (options) => {
  // 指定默认的头信息
  const defaultHeader = {}
  // 权限认证
  defaultHeader.Authorization = 'Bearer '+getApp().token
  // 合并头信息
  options.header = Object.assign({}, defaultHeader, options.header)
  // 拦截器处理后的请求参数
  return options
}
//响应拦截器
http.intercept.response=async ({data,config})=>{
  if(data.code===401){
    if(config.url.includes('/refreshToken')){
      const pageStack=getCurrentPages()
      const currentPage=pageStack.pop()
      const redirectURL=currentPage.route
      return wx.redirectTo({
        url: '/pages/login/index?redirectURL=/'+redirectURL,
      })
    }
    const app=getApp()
    //因为源码封装的只能有两个参数
    const res=await http({
      url: '/refreshToken',
      method:"POST",
      header:{
        Authorization: 'Bearer ' + app.refreshToken
      }
    })
    if(res.code!==10000) return wx.utils.toast('更新token失败!')
    app.setToken('token', res.data.token)
    app.setToken('refreshToken', res.data.refreshToken)
    config=Object.assign(config,{
      header:{
        Authorization: 'Bearer ' + res.data.token
      }
    })
   return http(config)
  }
  return data
}

export default http